<template>
  <div id="app">
    <h2 class="title">发布新课程</h2>
    <el-steps :space="500" :active="1" align-center finish-status="success">
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="提交审核"></el-step>
    </el-steps>
    <br /><br />
    <el-form ref="form" :model="courseInfo" label-width="80px">
      <el-form-item label="课程标题">
        <el-input
          placeholder="示例:机器学习项目课程:从基础到搭建项目视频课程。专业名称注意大小写"
          v-model="courseInfo.title"
        ></el-input>
      </el-form-item>
      <el-form-item label="课程类别">
        <!-- element-ui的级联选择器 -->
        <el-cascader
          :props="{ value: 'id' }"
          v-model="value"
          placeholder="请选择课程类别"
          :options="subjectTree"
          @change="handleChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择课程讲师">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="总课时">
        <el-input-number
          v-model="courseInfo.lessonNum"
          controls-position="right"
          @change="lessonChange"
          :min="1"
          :max="200"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="课程简介">
        <!-- ref="upload"  是关键 -->
        <quill-editor
          ref="upload"
          v-model="courseInfo.des"
          :options="editorOption"
        />
        <input type="file" @change="change" id="upload" style="display: none" />
      </el-form-item>
      <el-form-item label="课程封面">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8081/upload/pic"
          :on-success="success"
          :show-file-list="false"
        >
          <!-- v-bind:src -->
          <img v-if="courseInfo.cover" :src="courseInfo.cover" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="课程价格">
        <el-input-number
          v-model="courseInfo.price"
          controls-position="right"
          @change="priceChange"
          :precision="2"
          :step="0.1"
          :min="1"
          :max="700"
        ></el-input-number>
      </el-form-item>
      <el-form-item>
        <el-button class="next" type="primary" @click="next"
          >保存并下一步</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { quillEditor, Quill } from "vue-quill-editor";
import { container, ImageExtend } from "quill-image-extend-module";
Quill.register("modules/ImageExtend", ImageExtend);
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

export default {
  components: {
    quillEditor,
  },
  data() {
    return {
      teacherList: [],
      value: [],
      subjectTree: [],
      //这是第一种写法
      courseInfo: {
        id: "",
        title: "",
        subjectId: "",
        subjectParentId: "",
        teacherId: "",
        lessonNum: "",
        des: "",
        cover: "",
        price: "",
      },
      editorOption: {
        modules: {
          ImageExtend: {
            loading: true, // 可选参数 是否显示上传进度和提示语
            name: "img", // 图片参数名
            size: 3, // 可选参数 图片大小，单位为M，1M = 1024kb
          },
          toolbar: {
            container: container, // container为工具栏，此次引入了全部工具栏，也可自行配置
            handlers: {
              image: function (value) {
                if (value) {
                  //JavaScript代码对某个标签id设置点击事件
                  document.querySelector("#upload").click(); // 劫持原来的图片点击按钮事件
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
    };
  },
  created() {
    this.init();
  },
  watch: {
    $route(to, from) {
      this.init();
    },
  },
  methods: {
    init() {
      //得到所有课程分类
      this.getSubjectTree();
      //得到所有老师
      this.getTeacherAll();
      if (this.$route.params.id) {
        //根据id发送axios请求得到数据用于回显
        this.courseInfo.id = this.$route.params.id;
      } else {
        this.courseInfo = {
          id: "",
          title: "",
          subjectId: "",
          subjectParentId: "",
          teacherId: "",
          lessonNum: "",
          des: "",
          cover: "",
          price: "",
        };
        this.value=[];
      }
    },
    getSubjectTree() {
      this.$http.get("/subject/getSubjectTree").then((res) => {
        this.subjectTree = res.data.data;
        //根据课程id查询课程与课程描述信息
        this.getCourse(this.courseInfo.id);
      });
    },

    //选中的节点发生改变时触发这个函数
    handleChange(value) {
      this.courseInfo.subjectParentId = value[0];
      this.courseInfo.subjectId = value[1];
    },
    getTeacherAll(id) {
      this.$http.post("/teacher/getTeacherAll").then((res) => {
        console.log(res);
        this.teacherList = res.data.data;
      });
    },
    lessonChange(value) {
      this.courseInfo.lessonNum = value;
    },
    priceChange(value) {
      this.courseInfo.price = value;
    },
    change(e) {
      let file = e.target.files[0];
      const formData = new FormData();
      formData.append("file", file);
      this.$http.post("/upload/pic", formData).then((res) => {
        let quill = this.$refs.upload.quill;
        if (res.data.code == 200) {
          const formdata = _.extend({}, this.formdata);
          let length = quill.getSelection().index; //光标位置
          // 插入图片  图片地址
          quill.insertEmbed(length, "image", res.data.data);
          // 调整光标到最后
          quill.setSelection(length + 1); //光标后移一位
        }
      });
    },
    //课程封面上传完成回调
    success(res, file) {
      this.courseInfo.cover = res.data;
    },
    next() {
      let formData = new FormData();
      formData.append("title", this.courseInfo.title);
      formData.append("subjectId", this.courseInfo.subjectId);
      formData.append("subjectParentId", this.courseInfo.subjectParentId);
      formData.append("teacherId", this.courseInfo.teacherId);
      formData.append("lessonNum", this.courseInfo.lessonNum);
      formData.append("des", this.courseInfo.des);
      formData.append("cover", this.courseInfo.cover);
      formData.append("money", this.courseInfo.price);
      if (this.courseInfo.id) {
        formData.append("id", this.courseInfo.id);
        this.$http
        .post("/course/updateCourse", formData, {//修改
          Headers: {
            //key-value形式的响应头
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          this.$message({
            message: "修改课程基本信息成功",
            type: "success",
          });
          //1、把课程id作为参数发送到展示章节与小节页面去
          this.$router.push("/chapter/" + this.courseInfo.id);
        });
      } else {//添加
        this.$http
        .post("/course/addCourse", formData, {
          Headers: {
            //key-value形式的响应头
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          this.$message({
            message: "添加课程基本信息成功",
            type: "success",
          });
          //1、把课程id作为参数发送到展示章节与小节页面去
          this.$router.push("/chapter/" + res.data.data);
        });
      }
      
    },
    getCourse(id) {
      this.$http.get("/course/getCourse/" + id).then((res) => {
        this.courseInfo = res.data.data;
        let value = [res.data.data.subjectParentId,res.data.data.subjectId];
        this.value = value;
        this.courseInfo.subjectParentId=res.data.data.subjectParentId;
        this.courseInfo.subjectId=res.data.data.subjectId;
        this.courseInfo.price = res.data.data.price/100;
      });
    },
  },
};
</script>

<style scoped>
.title {
  margin: 20px;
  text-align: center;
}
.el-cascader {
  width: 320px;
}
:deep().ql-container {
  height: 300px;
}
.avatar-uploader :deep() .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader :deep() .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.next {
  margin-bottom: 20px;
}
</style>
